package com.andy.wang.service.impl;

import com.andy.wang.pojo.Result;
import com.andy.wang.session.UserSession;
import com.andy.wang.utils.UploadFile;
import com.andy.wang.utils.redis.RedisUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.andy.wang.pojo.User;
import com.andy.wang.service.UserService;
import com.andy.wang.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 王更元
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-04-02 11:33:38
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    List<User> users = null;
    @Autowired
    private UserMapper userMapper;

    @Override
    public int insertSelective(User user, String imgType) {
        byte[] bytes = null;
        String uploadFile = "";
        //        判断前端传的是1还是2要是1的话为男2的话为女
        if (user.getUSex().equals("1")) {
            user.setUSex("男");
        } else {
            user.setUSex("女");
        }
        if (user.getUphoto().equals("")) {
            user.setUphoto("https://test01-1324045941.cos.ap-beijing.myqcloud.com/test/20240329134346_1.7406552305985335E8.jpg");
        } else {
            try {
                bytes = Base64Utils.decode(user.getUphoto().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
//            System.out.println(Base64.getDecoder().decode(user.getUphoto()));
            uploadFile = UploadFile.uploadFile(bytes, UUID.randomUUID().toString() + "." + imgType);
            user.setUphoto(uploadFile);
        }
//        System.out.println(user.getUphoto());
        // 设置个性背景图片
        user.setSignatureIMG("https://tse1-mm.cn.bing.net/th/id/OIP-C.d95XU9rPpliLu_FNqV9hHQHaFN?rs=1&pid=ImgDetMain");
        //处理最后一位，
        user.setUhobby(user.getUhobby().substring(0, user.getUhobby().length() - 1));
        return userMapper.insert(user);
    }

    //使用Redis存储用户数据
    @Override
    public User sessionPhone(String phone, HttpServletRequest request) {
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<User>();
        query.eq(User::getUPhone, phone);
        User user = userMapper.selectOne(query);
        request.getSession().setAttribute(UserSession.uPhone,user.getUPhone());
        return user;
    }


    @Override
    public List<User> selectUhobbys(Long uid, String uhobbys) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.ne(User::getUid, uid)
                .and(i -> i.apply("FIND_IN_SET('" + uhobbys + "',uhobby)>0").or().like(!uhobbys.contains(","), User::getUName, uhobbys));
        return userMapper.selectList(userLambdaQueryWrapper);
    }

    // 查询全部
    public List<User> selectAll(ArrayList<Long> uIds) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(uIds.size() > 0) {
            for (int i = 0; i < uIds.size(); i++) {
                userLambdaQueryWrapper.ne(User::getUid, uIds.get(i));
            }
        }
        return userMapper.selectList(userLambdaQueryWrapper);
    }

    @Override
    public List<User> QueryRecommendation(Long uid, String uhobbys, int count, String search) {
        ArrayList<Long> uIds = new ArrayList<>();
        users = new ArrayList<>();

        List<User> lazyUsers = new ArrayList<>();

        if (StringUtils.isNotBlank(search)) {
            uhobbys = search;
        }

        // 范围查询 先判断他是否有多个值
        if (uhobbys.contains(",")) {
            // 有多个值
            // 完全匹配的查询
            List<User> smallUserList = this.selectUhobbys(uid, uhobbys);
            for (int index = 0; index < smallUserList.size(); index++) {
                if (uIds.size() == 0) {
                    uIds.add(smallUserList.get(index).getUid());
                    users.add(smallUserList.get(index));
                } else {
                    for (int index2 = 0; index2 < uIds.size(); index2++) {
                        if (smallUserList.get(index).getUid() != uIds.get(index2)) {
                            uIds.add(smallUserList.get(index).getUid());
                            users.add(smallUserList.get(index));
                        }
                    }
                }
            }

            String[] uhobbyArray = uhobbys.split(",");
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            for (int i = 0; i < uhobbyArray.length; i++) {
                String uhobby = uhobbyArray[i];
                userLambdaQueryWrapper.apply("FIND_IN_SET('" + uhobby + "',uhobby) > 0").or();
                if (i + 1 == uhobbyArray.length) {
                    List<User> userList = userMapper.selectList(userLambdaQueryWrapper);
                    if (uIds.size() > 0) {
                        for (int Lindex = 0; Lindex < userList.size(); Lindex++) {
                            for (int index = 0; index < uIds.size(); index++) {
                                if (userList.get(Lindex).getUid() != uid) {
                                    if (userList.get(Lindex).getUid() != uIds.get(index)) {
                                        uIds.add(userList.get(Lindex).getUid());
                                        users.add(userList.get(Lindex));
                                    }
                                }
                            }
                        }
                    } else {
                        for (int index = 0; index < userList.size(); index++) {
                            if (userList.get(index).getUid() != uid) {
                                uIds.add(userList.get(index).getUid());
                                users.add(userList.get(index));
                            }
                        }
                    }
                }
            }
            if (StringUtils.isBlank(search)) {
                List<User> userList = this.selectAll(uIds);
                for (int index = 0; index < userList.size(); index++) {
                        uIds.add(userList.get(index).getUid());
                        users.add(userList.get(index));
                }
            }
            int i = 1;
            for (int index = 0; index < users.size(); index++) {
                if (i <= count) {
                    i++;
                    lazyUsers.add(users.get(index));
                } else {
                    break;
                }
            }
            System.out.println(lazyUsers.size());
            return lazyUsers;
        } else {
            // 完全匹配的查询
            List<User> smallUserList = this.selectUhobbys(uid, uhobbys);
            for (int index = 0; index < smallUserList.size(); index++) {
                uIds.add(smallUserList.get(index).getUid());
                users.add(smallUserList.get(index));
            }

            if (StringUtils.isBlank(search)) {
                List<User> userList = this.selectAll(uIds);
                for (int index = 0; index < userList.size(); index++) {
                    uIds.add(userList.get(index).getUid());
                    users.add(userList.get(index));
                }
            }

            int i = 1;
            for (int index = 0; index < users.size(); index++) {
                if (i <= count) {
                    i++;
                    lazyUsers.add(users.get(index));
                } else {
                    break;
                }
            }
            return lazyUsers;
        }
    }

    @Override
    public int QueryCountNumber() {
        return users.size();
    }

    @Override
    public int updateUser(HttpServletRequest request, User user, String imgType,String Phone) {
        byte[] bytes = null;
        String uploadFile = "";
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUPhone, Phone);
        User uPhoto = this.getOne(lambdaQueryWrapper);

        if (!user.getUphoto().equals(uPhoto.getUphoto())) {
            try {
                bytes = Base64Utils.decode(user.getUphoto().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            uploadFile = UploadFile.uploadFile(bytes, UUID.randomUUID().toString() + "." + imgType);
            user.setUphoto(uploadFile);
        }
        return userMapper.updateUser(user);
    }

    @Override
    public int deleteUser(Integer id) {
        return userMapper.deleteUser(id);
    }
}




